package oceanwiki.websocketserver;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;

/**
 * @FileName WebSocketServer
 * @Description
 * @Author Me
 * @date 2024-09-20
 **/

@Component
@ServerEndpoint("/ws/{token}")
public class WebSocketServer {
    private static final Logger LOG = LoggerFactory.getLogger(WebSocketServer.class);

    //每个客户端的token
    private String token = "";

    private static HashMap<String, Session> map = new HashMap<>();

    //链接成功
    @OnOpen
    public void open(Session session, @PathParam("token")String token) {
        map.put(token, session);
        this.token = token;
        LOG.info("有新链接：token:{}, session id:{}, 当前链接数：{}", token, session.getId(), map.size());
    }

    //链接关闭
    @OnClose
    public void onClose(Session session) {
        map.remove(this.token);
        LOG.info("链接关闭：token:{}, session id:{}, 当前链接数：{}", this.token, session.getId(), map.size());
    }

    //收到消息
    @OnMessage
    public void onMessage(String message, Session session) {
        LOG.info("收到消息：{}, 内容：{}", token, message);
    }

    //报错时
    @OnError
    public void onError(Session session, Throwable error) {
        LOG.info("发生错误", error);
    }

    //群发消息
    public void sendInfo(String message) {
        for (String token:map.keySet()) {
            Session session = map.get(token);
            try {
                session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                LOG.info("推送消息失败：{}, 内容：{}", token, message);
            }
            LOG.info("推送消息：{}, 内容：{}", token, message);
        }
    }
}
